<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统</title>
    <!-- 引入 Element UI 样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入 Vue -->
    <script src="js/vue@2.js"></script>
    <!-- 引入 Element UI 组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- 引入 ECharts -->
    <script src="js/echarts.min.js"></script>
    <script src="js/axios.min.js"></script>
    <style>
        [v-cloak] {
            display: none;
        }

        .app-container {
            display: flex;
            height: 100vh;
        }

        .app-aside {
            background: #2d3a4b;
            padding: 0;
            height: 100vh;
            color: white;
        }

        .app-menu {
            height: 100%;
        }

        .app-header {
            background: #409EFF;
            color: white;
            text-align: center;
            line-height: 60px;
            height: 60px;
        }

        .app-main {
            padding: 20px;
            overflow: auto;
        }

        .statistic-item {
            display: inline-block;
            width: 23%;
            margin-right: 1%;
            margin-bottom: 20px;
            text-align: center;
        }

        .statistic-item i {
            font-size: 48px;
        }

        .charts-container {
            display: flex;
        }

        #gender-chart, #user-trend-chart {
            width: 50%;
            height: 400px;
        }
    </style>
</head>
<body>
<div id="app" class="app-container" v-cloak>
    <!-- 左侧导航栏 -->
    <el-aside width="200px" class="app-aside">
        <el-menu class="app-menu" :default-openeds="['1']">
            <el-submenu index="1">
                <template slot="title">
                    <i class="el-icon-menu"></i>
                    <span>菜单</span>
                </template>
                <el-menu-item index="1-1" @click="navigateTo('Admin_index.html')">
                    <i class="el-icon-s-data"></i>仪表盘
                </el-menu-item>
                <el-menu-item index="1-2" @click="navigateTo('Admin_user.html')">
                    <i class="el-icon-user"></i>用户管理
                </el-menu-item>
                <el-menu-item index="1-3" @click="navigateTo('settings.html')">
                    <i class="el-icon-setting"></i>设置
                </el-menu-item>
                <el-menu-item index="1-4" @click="navigateTo('Admin_wenda.html')">
                    <i class="el-icon-question"></i>问答管理
                </el-menu-item>
                <el-menu-item index="1-5" @click="navigateTo('Admin_gonggao.html')">
                    <i class="el-icon-message"></i>公告管理
                </el-menu-item>
                <el-menu-item index="1-6" @click="navigateTo('Admin_gouwuche.html')">
                    <i class="el-icon-shopping-cart-full"></i>购物车管理
                </el-menu-item>

            </el-submenu>
        </el-menu>
    </el-aside>

    <!-- 右侧操作区域 -->
    <el-container>
        <el-header class="app-header">后台管理系统</el-header>
        <el-main class="app-main">
            <!-- 数据统计卡片 -->
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span>数据统计</span>
                </div>
                <div class="charts-container">
                    <div id="gender-chart"></div>
                    <div id="user-trend-chart"></div>
                </div>
            </el-card>
            <!-- 数据统计 -->
            <div class="statistic-item">
                <el-card>
                    <i class="el-icon-user"></i>
                    <h3>用户数</h3>
                    <p>{{ statistics.userNum }}</p>
                </el-card>
            </div>
            <div class="statistic-item">
                <el-card>
                    <i class="el-icon-bell"></i>
                    <h3>公告数</h3>
                    <p>{{ statistics.gonggaoNum }}</p>
                </el-card>
            </div>
            <div class="statistic-item">
                <el-card>
                    <i class="el-icon-question"></i>
                    <h3>问答数</h3>
                    <p>{{ statistics.wendaNum }}</p>
                </el-card>
            </div>
            <div class="statistic-item">
                <el-card>
                    <i class="el-icon-tickets"></i>
                    <h3>图书数量</h3>
                    <p>{{ statistics.booksNum }}</p>
                </el-card>
            </div>
            <!-- 操作 -->
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span>操作</span>
                </div>

                <el-table :data="tableData" style="width: 100%;" stripe border>
                    <el-table-column prop="id" label="ID" width="200"></el-table-column>
                    <el-table-column prop="username" label="用户名" width="250"></el-table-column>
                    <el-table-column prop="time" label="时间" width="400">
                        <template v-slot="scope">
                            {{ WenDaformatDate( scope.row.time) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="action" label="动作" width="250"></el-table-column>
                </el-table>

                <!--   <el-table :data="tableData" style="width: 100%;" stripe border>
                       <el-table-column prop="id" label="ID" width="100"></el-table-column>
                       <el-table-column prop="profile" label="头像" width="100">
                           <template slot-scope="scope">
                               <img :src="scope.row.profile" alt="头像"
                                    style="width: 50px; height: 50px; border-radius: 50%;">
                           </template>
                       </el-table-column>
                       <el-table-column prop="name" label="姓名" width="180"></el-table-column>
                       <el-table-column prop="username" label="用户名" width="180"></el-table-column>
                       <el-table-column prop="password" label="密码" width="180"></el-table-column>
                       <el-table-column prop="balance" label="余额" width="120"></el-table-column>
                       <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
                       <el-table-column prop="sex" label="性别" width="100"></el-table-column>
                       <el-table-column prop="create_time" label="创建时间" width="180"></el-table-column>
                   </el-table>
   -->


                <!--    <el-form ref="form" :model="form" label-width="120px" style="margin-top: 20px;">
                        <el-form-item label="用户名">
                            <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
                        </el-form-item>
                        <el-form-item label="姓名">
                            <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
                        </el-form-item>
                        <el-form-item label="性别">
                            <el-select v-model="form.sex" placeholder="请选择性别">
                                <el-option label="男" value="male"></el-option>
                                <el-option label="女" value="female"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="邮箱">
                            <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
                        </el-form-item>
                        <el-form-item label="创建时间">
                            <el-date-picker
                                    v-model="form.create_time"
                                    type="date"
                                    placeholder="请选择日期"
                                    format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="onSubmit">提交</el-button>
                            <el-button @click="onReset">重置</el-button>
                        </el-form-item>
                    </el-form>-->


            </el-card>
        </el-main>
    </el-container>
</div>
<script src="js/data.js"></script>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                statistics: {
                    userNum: -1,// 用户数
                    gonggaoNum: -1,// 公告数
                    wendaNum: -1,// 问答数
                    booksNum: -1// 图书数量
                },
                //用户数据
                tableData: [],
                form: {
                    // profile: '',
                    name: '',
                    username: '',
                    //  password: '',
                    //   balance: '',
                    email: '',
                    sex: '',
                    create_time: ''
                }
            }
        },
        methods: {
            WenDaformatDate(isoString) {
                const date = new Date(isoString);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0'); // getMonth() 返回值为 0-11
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}`;
            },
            ToGetGenderCounts() {
                axios.get(urlluodeng + '/user/GetGenderCounts').then(res => {
                    if (res.data.result) {
                        console.log(res.data.data);
                        const {maleCount, femaleCount} = res.data.data;
                        const SexData = [
                            {value: maleCount, name: '男'},
                            {value: femaleCount, name: '女'}
                        ];
                        this.getSexChart(SexData);
                    } else {
                        this.$message.error("错误");
                    }
                }).catch(err => {
                    console.log(err);
                    this.$message.error('网络错误，请稍后再试！');
                });

            }, DOUserRecordZheXianTu(registrationCountsList, cancellationCountsList) {
                // 用户趋势折线图
                var userTrendChart = echarts.init(document.getElementById('user-trend-chart'));
                var userTrendOption = {
                    title: {
                        text: '最近30天用户趋势',
                        x: 'center'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: ['注册数量', '注销数量'],
                        bottom: 0                  // 将图例放在底部
                    },
                    xAxis: {
                        type: 'category',
                        data: getLast30DaysDates()
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name: '注册数量',
                            type: 'line',
                            data: registrationCountsList,
                            itemStyle: {
                                color: 'green'
                            }
                        },
                        {
                            name: '注销数量',
                            type: 'line',
                            data: cancellationCountsList,
                            itemStyle: {
                                color: 'red'
                            }
                        }
                    ]
                };
                userTrendChart.setOption(userTrendOption);

            },
            getUserRecordData() {
                // 获取用户注册、注销数据
                axios.get(urlluodeng + '/userrecord/getAlluserrecord').then(res => {
                    if (res.data.result) {
                        console.log("用户记录数据获取成功：");
                        console.log(res.data.data);
                        // 注册、注销数量
                        const {registrationCountsList, cancellationCountsList} = get30DaysActivityLists(res.data.data);
                        console.log("注册列表：" + registrationCountsList);
                        console.log("注销列表：" + cancellationCountsList);


                        this.DOUserRecordZheXianTu(registrationCountsList, cancellationCountsList);
                        this.tableData = res.data.data;
                    } else {
                        this.$message.error('获取数据失败，请稍后再试！');
                    }
                }).catch(err => {
                    console.log(err);    // 错误处理
                    this.$message.error('网络错误，请稍后再试！');
                });


            },

            navigateTo(page) {
                window.location.href = page; // 使用参数指定跳转页面路径
            },
            onSubmit() {
                console.log('提交!', this.form);
            },
            generateDateRange() {
                const dateList = [];
                const now = new Date();
                for (let i = 29; i >= 0; i--) {
                    const date = new Date(now - i * 24 * 60 * 60 * 1000);
                    const month = date.getMonth() + 1;
                    const day = date.getDate();
                    dateList.push(`${month}-${day}`);
                }
                return dateList;
            },
            generateUserData() {
                //生成一个包含 30 个介于 0 到 99（含）之间随机整数的数组
                return Array.from({length: 30}, () => Math.floor(Math.random() * 100));
            },
            onReset() {
                this.form = {
                    name: '',
                    username: '',
                    email: '',
                    sex: '',
                    create_time: ''
                }
            },
            getSexChart(SexData) {
                /*[
                    {value: 235, name: '男'},
                    {value: 135, name: '女'},
                        ]*/
                // 男女比例饼图
                var genderChart = echarts.init(document.getElementById('gender-chart'));
                var genderOption = {
                    title: {

                        text: '男女占比',
                        x: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b} : {c} ({d}%)'
                    },
                    series: [
                        {
                            name: '性别',
                            type: 'pie',
                            radius: '55%',
                            center: ['50%', '60%'],
                            data: SexData

                            ,
                            itemStyle: {
                                emphasis: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                };
                genderChart.setOption(genderOption);
            },

        },
        mounted() {

            /*   [{
                   "id": 1,
                   "username": "123",
                   "time": "2021-01-01 12:00:00",
                   "do": "注册"
               },
                   {
                       "id":2,
                       "username": "222",
                       "time": "2021-01-03 12:00:00",
                       "do": "注销"
                   },
                   ....
               ]*/


        },
        created() {
            //检查是否已经登录
            axios.post(urlluodeng + '/admin/GetLoginUserInfo').then(res => {

                if (res.data.result) {


                    // 获取数据
                    axios.get(urlluodeng + '/data/fourTableTongJi').then(res => {
                        if (res.data.result) {
                            console.log(res.data.data);
                            /*
                            *  results.put("userCount", (Integer) params.get("userCount"));
                                results.put("gonggaoCount", (Integer) params.get("gonggaoCount"));
                                results.put("bookCount", (Integer) params.get("bookCount"));
                                results.put("wendaCount", (Integer) params.get("wendaCount"));
                            * */
                            this.statistics.userNum = res.data.data.userCount;
                            this.statistics.gonggaoNum = res.data.data.gonggaoCount;
                            this.statistics.wendaNum = res.data.data.wendaCount;
                            this.statistics.booksNum = res.data.data.bookCount;
                        } else {
                            this.$message.error(res.data.msg);
                        }
                    }).catch(err => {
                        console.log(err);    // 错误处理
                        this.$message.error('网络错误，请稍后再试！');
                    });

                    this.getUserRecordData();
                    this.ToGetGenderCounts();

                } else {
                    //用户未登录
                    this.$message.error('401 未授权，请先登录');
                    setTimeout(() => {
                        window.location.href = 'Admin_login.html';
                    }, 500)
                }
            }).catch(err => {
                console.log(err);
                this.$message.error('网络错误，请稍后再试！');
                setTimeout(() => {
                    window.location.href = 'Admin_login.html';
                }, 500)
            });
        }
    })
</script>
</body>
</html>
